package cn.iocoder.yudao.module.system.service.gugu;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeScoreInfo;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.CollegeScoreQueryReqVO;
import cn.iocoder.yudao.module.system.controller.admin.gugu.vo.CollegeScorePageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.CollegeScoreDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.CollegeScoreMapper;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历年高考高校录取分数线数据 Service 实现类
 */
@Service
@Slf4j
public class CollegeScoreServiceImpl implements CollegeScoreService {

    @Resource
    private CollegeScoreMapper collegeScoreMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveCollegeScoreList(List<CollegeScoreInfo> collegeScoreList) {
        if (collegeScoreList == null || collegeScoreList.isEmpty()) {
            return 0;
        }

        int savedCount = 0;
        for (CollegeScoreInfo info : collegeScoreList) {
            // 检查是否已存在相同的记录
            boolean exists = existsCollegeScore(info.getProvince(), info.getYear(), 
                    info.getSchoolUuid(), info.getAdmissionBatch(), info.getTypeName());
            
            if (!exists) {
                CollegeScoreDO collegeScore = CollegeScoreDO.builder()
                        .province(info.getProvince())
                        .schoolUuid(info.getSchoolUuid())
                        .collegeName(info.getCollegeName())
                        .year(info.getYear())
                        .highestScore(info.getHighestScore())
                        .averageScore(info.getAverageScore())
                        .lowestScore(info.getLowestScore())
                        .lowestRank(info.getLowestRank())
                        .provincialControlLine(info.getProvincialControlLine())
                        .enrollmentType(info.getEnrollmentType())
                        .selectionLevel(info.getSelectionLevel())
                        .admissionBatch(info.getAdmissionBatch())
                        .typeName(info.getTypeName())
                        .courseSelection(info.getCourseSelection())
                        .courseSelectionName(info.getCourseSelectionName())
                        .schoolType(info.getSchoolType())
                        .schoolInCity(info.getSchoolInCity())
                        .is985(info.getIs985())
                        .is211(info.getIs211())
                        .isDualClass(info.getIsDualClass())
                        .coverImage(info.getCoverImage())
                        .build();
                
                collegeScoreMapper.insert(collegeScore);
                savedCount++;
            } else {
                log.debug("高校录取分数线数据已存在，跳过保存: 省份={}, 年份={}, 高校UUID={}, 录取批次={}, 文科理科类型={}", 
                        info.getProvince(), info.getYear(), info.getSchoolUuid(), info.getAdmissionBatch(), info.getTypeName());
            }
        }

        return savedCount;
    }

    @Override
    public List<CollegeScoreDO> getCollegeScoreList(String province, Integer year, String collegeName) {
        return collegeScoreMapper.selectByProvinceYearAndCollegeName(province, year, collegeName);
    }

    @Override
    public List<CollegeScoreDO> getCollegeScoreByProvince(String province) {
        return collegeScoreMapper.selectByProvince(province);
    }

    @Override
    public List<CollegeScoreDO> getCollegeScoreByYear(Integer year) {
        return collegeScoreMapper.selectByYear(year);
    }

    @Override
    public List<CollegeScoreDO> getCollegeScoreByCollegeName(String collegeName) {
        return collegeScoreMapper.selectByCollegeName(collegeName);
    }

    @Override
    public List<CollegeScoreDO> getCollegeScoreBySchoolUuid(String schoolUuid) {
        return collegeScoreMapper.selectBySchoolUuid(schoolUuid);
    }

    @Override
    public PageResult<CollegeScoreDO> getCollegeScorePage(CollegeScorePageReqVO reqVO) {
        return collegeScoreMapper.selectPage(reqVO);
    }

    @Override
    public boolean existsCollegeScore(String province, Integer year, String schoolUuid, String admissionBatch, String typeName) {
        return collegeScoreMapper.existsByCondition(province, year, schoolUuid, admissionBatch, typeName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> fetchAndSaveCollegeScore(String appkey, String searchtype, String keyword, Integer year, Integer pageindex, Integer pagesize) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证API Key
            if (!GuGuDataUtils.validateCollegeScoreApiKey(appkey)) {
                result.put("success", false);
                result.put("message", "无效的API Key");
                return result;
            }

            // 构建查询参数
            CollegeScoreQueryReqVO reqVO = new CollegeScoreQueryReqVO();
            reqVO.setSearchtype(searchtype);
            reqVO.setKeyword(keyword);
            reqVO.setYear(year);
            reqVO.setPageindex(pageindex != null ? pageindex : 1);
            reqVO.setPagesize(pagesize != null ? pagesize : 10);

            // 调用API获取数据
            Map<String, Object> apiResult = GuGuDataUtils.getCollegeScoreInfo(reqVO);

            if (!Boolean.TRUE.equals(apiResult.get("success"))) {
                result.put("success", false);
                result.put("message", "API调用失败: " + apiResult.get("message"));
                return result;
            }

            @SuppressWarnings("unchecked")
            List<CollegeScoreInfo> collegeScoreList = (List<CollegeScoreInfo>) apiResult.get("collegeScoreList");

            if (collegeScoreList == null || collegeScoreList.isEmpty()) {
                result.put("success", true);
                result.put("message", "未获取到数据");
                result.put("savedCount", 0);
                result.put("totalCount", 0);
                result.put("apiTotalCount", apiResult.get("totalCount"));
                return result;
            }

            // 保存到数据库
            int savedCount = saveCollegeScoreList(collegeScoreList);

            result.put("success", true);
            result.put("message", "成功获取并保存高校录取分数线数据");
            result.put("savedCount", savedCount);
            result.put("totalCount", collegeScoreList.size());
            result.put("apiTotalCount", apiResult.get("totalCount"));

            return result;
        } catch (Exception e) {
            log.error("获取并保存高校录取分数线数据失败", e);
            result.put("success", false);
            result.put("message", "获取并保存高校录取分数线数据失败: " + e.getMessage());
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCollegeScore(String province, Integer year, String schoolUuid, String admissionBatch, String typeName) {
        return collegeScoreMapper.deleteByCondition(province, year, schoolUuid, admissionBatch, typeName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteCollegeScoreByYear(Integer year) {
        return collegeScoreMapper.deleteByYear(year);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createCollegeScore(CollegeScoreDO createReqVO) {
        collegeScoreMapper.insert(createReqVO);
        return createReqVO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCollegeScore(CollegeScoreDO updateReqVO) {
        collegeScoreMapper.updateById(updateReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCollegeScore(Long id) {
        collegeScoreMapper.deleteById(id);
    }

    @Override
    public CollegeScoreDO getCollegeScore(Long id) {
        return collegeScoreMapper.selectById(id);
    }
}
